#include "widget.h"
#include "ui_widget.h"
#include <QUdpSocket>
#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置窗口标题
    this->setWindowTitle("服务器");

    //创建udp服务器
    udp = new QUdpSocket(this);

    //绑定信号槽
    connect(udp,&QUdpSocket::readyRead,this,&Widget::handleRequest);

    //bind
    bool ret = udp->bind(QHostAddress::AnyIPv4,8080);
    if(!ret){
        QMessageBox::critical(this,"bind error,",udp->errorString());
        return;
    }

}

Widget::~Widget()
{
    udp->close();
    delete ui;
}

//解析请求数据报
QString Widget::analyze(const QNetworkDatagram &request)
{
    return request.data();
}


void Widget::handleRequest()
{
    //读取对端发来的请求信息
    const QNetworkDatagram &dataGramResquest = udp->receiveDatagram();

    //对请求信息进行解析并构建响应 （由于我们是echo服务器，对端发送来的数据，就是我们要发送的响应）
    const QString &response = analyze(dataGramResquest);
    QNetworkDatagram dataGramResponse(response.toUtf8(),dataGramResquest.senderAddress(),dataGramResquest.senderPort());

    //发送响应报文
    udp->writeDatagram(dataGramResponse);

    //将客户端发送的信息显示到窗口的控件上
    QString log = "[ " + dataGramResquest.senderAddress().toString() + ":" + QString::number(dataGramResquest.senderPort()) + "]" + \
                  "# " + response;
    ui->listWidget->addItem(log);
}



